package com.filetransfer.app.ui.upload;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.filetransfer.api.ShareCollection;
import com.filetransfer.app.R;
import com.filetransfer.app.db.HistoryDatabaseHelper;

import java.net.URL;

import lombok.extern.slf4j.Slf4j;
@Slf4j
public class UploadActivity extends AppCompatActivity {
    private FileAdapter fileAdapter;
    private ActivityResultLauncher<Intent> filePickerLauncher;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.upload);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        RecyclerView recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        fileAdapter = new FileAdapter(position -> {
            if (fileAdapter.isEmpty()) {
                // 当删除所有文件后自动返回
                finish();
            }
        });
        recyclerView.setAdapter(fileAdapter);
        findViewById(R.id.addButton).setOnClickListener(v -> chooseFile());
        findViewById(R.id.submitButton).setOnClickListener(v -> submit());
        filePickerLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode() == RESULT_OK && result.getData() != null && result.getData().getData() != null) {
                Uri selectedUrl = result.getData().getData();
                fileAdapter.addFile(this, selectedUrl);
                fileAdapter.notifyDataSetChanged();
            }
        });
        chooseFile();
    }
    @Override
    public boolean onSupportNavigateUp() {
        finish(); // 当点击顶部的返回按钮
        return true;
    }
    private void chooseFile() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        filePickerLauncher.launch(Intent.createChooser(intent, "选择文件"));
    }
    private void submit() {
        try {
            fileAdapter.makeShare(result -> {
                if (result != null) {
                    runOnUiThread(() -> {
                        try (var db = new HistoryDatabaseHelper(this)) {
                            for (URL link : result.links()) {
                                db.insert(link.toString(), link.getPath(), result.share().getCode(), "上传成功", String.valueOf(System.currentTimeMillis()));
                            }
                        }
                        var dialog = new ShareResultDialog(this,
                                new ShareCollection.ShareResult(result.share(), result.links())
                                , di -> {
                            finish();
                        });
                        dialog.show();
                        fileAdapter.clear();
                    });
                }
            }, error -> {
            });
        } catch (Exception e) {
            log.error(e.getMessage());
            log.error("error", e);
        }
    }
}
